package com.kongshidian.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.RelativeLayout;

import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.Product;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.ProductListActivity.ProductListAdapter;
import com.kongshidian.ui.view.DoubleButtonDialog;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.kongshidian.util.ContextUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

/** 收藏 */
public class FollowActivity extends BackableTitleBarActivity implements OnItemLongClickListener{
	private PullToRefreshGridView mGv  	= null;
	private RefreshViewLoadMoreProxy mProxy = null;
	private int mPageNow  				= 0;
	private RelativeLayout mEmptyRelat;
	private DoubleButtonDialog mDoubleDialog;
	private Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_follow);
		getTitleBar().setTitle(R.string.title_activity_follow);

		mEmptyRelat = (RelativeLayout) findViewById(R.id.follow_empty_relat);
		mGv = (PullToRefreshGridView) findViewById(R.id.ptr_gv);
		mGv.setEmptyView(mEmptyRelat);
		mGv.getRefreshableView().setSelector(android.R.color.transparent);
		mGv.getRefreshableView().setOnItemLongClickListener(this);
		mGv.setAdapter(new ProductListActivity.ProductListAdapter(this, R.layout.list_item_products));
		mGv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(FollowActivity.this, ProductDetailActivity.class);
				intent.putExtra("productID", ((Product) mGv.getRefreshableView().getAdapter().getItem(position)).getId() + "");
				startActivityForResult(intent, 0);
			}
		});

		mProxy = new RefreshViewLoadMoreProxy(mGv, Mode.BOTH, 0, 0);
		mProxy.setOnLoadDataActionListener(new OnLoadDataActionListener() {

			@Override
			public void onRefresh(int page) { // 下拉
				mPageNow = 1;
				new GetData().execute(true);
			}

			@Override
			public void onLoadMore(int page) { // 上拉
				++ mPageNow;
				new GetData().execute(false);
			}
		});
		mProxy.refreshing();
	}

	// param：isRefresh
	private class GetData extends AsyncTask<Boolean, Void, Boolean> {
		private List<Product> mProducts 	= null;

		@Override
		protected Boolean doInBackground(Boolean... params) {
			try {
				PageEntity<Product> entity = WebClient.getInstance(FollowActivity.this).favoriteList(mPageNow, 20, "id", "desc");

				mProducts = entity.getContent();

				if(mPageNow > entity.getTotalPages()){
					App.showShortToast(R.string.the_end_page);
					mProducts = null;
				}
			} catch (WebException e) {
				if(WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()) ){
					mProducts = null;
				}else if("shop.common.unauthorized".equals(e.getStatusCode())){
					ContextUtil.startActivity(FollowActivity.this, LoginActivity.class);
					finish();	
				}else {
					e.printStackTrace();
				}
			}
			return params[0];
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result) 	// refresh
				((ProductListAdapter) mGv.getRefreshableView().getAdapter()).update(mProducts);
			else 			// append
				((ProductListAdapter) mGv.getRefreshableView().getAdapter()).append(mProducts);

			mGv.onRefreshComplete();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0 && resultCode == RESULT_OK)
			mPageNow = 1;
		new GetData().execute(true);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
			long id) {
		long pid = ((ProductListAdapter) mGv.getRefreshableView().getAdapter()).getData().get(position).getId();
		showDeleteFavoriteDialog(pid);
		return true;
	}

	/** 显示删除框 */
	private void showDeleteFavoriteDialog(final long ids) {
		dismissDeleteFavoriteDialog();
		mDoubleDialog = new DoubleButtonDialog(this);
		mDoubleDialog.showDialog(getString(R.string.info_delete_favorite), new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				new Thread(){
					public void run() {
						try {
							WebClient.getInstance(FollowActivity.this).favoriteDelete(ids);
							mHandler.sendEmptyMessage(0);
						} catch (WebException e) {
							//	e.printStackTrace();
						}catch (Exception e) {

						}	
					};
				}.start();

			}
		});

	}
	/** 取消dialog */
	private void dismissDeleteFavoriteDialog() {
		if( mDoubleDialog != null && mDoubleDialog.isShowing() ) {
			mDoubleDialog.dismiss();
		}
		mDoubleDialog = null;

	}

	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					mPageNow = 1;
					new GetData().execute(true);
					break;
				default:
					break;
				}
			}
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismissDeleteFavoriteDialog();
		mHandler.removeCallbacksAndMessages(null);
	}


}
